package com.scfire.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
/*import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;*/
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/** 
 * Copyright 2015 Shudao Info Tech Co. Ltd.  All rights reserved.
 * @author lhzeng
 * @email zenglh@haoshudao.com
 * @date 2015年6月7日 下午2:44:39 
 * @version V1.0
 */

public class HttpUtil {
	
	public static String httpRequest(String url) {
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		HttpGet httpGet = new HttpGet(url);
		
		httpGet.addHeader("max-age",String.valueOf(Integer.MAX_VALUE));
		httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		httpGet.addHeader("Accept-Encoding", "gzip,deflate,sdch");
		httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,es;q=0.4");
		httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");
		try {			
			HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
			
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {
				String content = EntityUtils.toString(entity,"UTF-8");							
				return content;
			}
		} catch (IOException e) {
					
		} finally {
			try {
				closeableHttpClient.close();
			} catch (IOException e) {
			}
		}
		return null;
	}

	public static String getHttpGetResponse(String url,Map<String,String> header) {
        HttpClient httpclient = new DefaultHttpClient();  
        HttpGet httpgets = new HttpGet(url);
        
        if(header != null) {
        	Iterator<String> it = header.keySet().iterator();
        	while(it.hasNext()) {
        		String key = it.next();
        		String value = header.get(key);
        		httpgets.addHeader(key, value);
        	}
        }
        
        String result = null;
        
		try {
			HttpResponse response = httpclient.execute(httpgets);
			HttpEntity entity = response.getEntity(); 
			if (entity != null) {  
				result = EntityUtils.toString(entity, "utf-8");
	            httpgets.abort();    
	        }  
		} catch (IOException e) {
			e.printStackTrace();
		}    
		return result;
        
	}
	
	/**
	 * InputStream
	 * @param is
	 * @return
	 */
	public static String convertStreamToString(InputStream is) {      
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
        StringBuilder sb = new StringBuilder();      
       
        String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {  
                sb.append(line + "\n");      
            }      
        } catch (IOException e) {      
            e.printStackTrace();      
        } finally {      
            try {      
                is.close();      
            } catch (IOException e) {      
               e.printStackTrace();      
            }      
        }      
        return sb.toString();      
    }
	public static String sf(String url,String json) throws Exception{
		String APPLICATION_JSON = "application/json";
		String CONTENT_TYPE_TEXT_JSON = "text/json";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);

		 if(json!= null && !"".equals(json)) {
	        	String encoderJson = null;
//	    		try {
//	    			encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
//	    		} catch (UnsupportedEncodingException e2) {
//	    			e2.printStackTrace();
//	    		}
	        	
	    		httppost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
	            
	            StringEntity se = null;
	    		try {
	    			se = new StringEntity(json,"utf-8");
	    		} catch (Exception e1) {
	    			e1.printStackTrace();
	    		}
	            se.setContentType(CONTENT_TYPE_TEXT_JSON);
	            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
	            httppost.setEntity(se);
	        }
        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
            InputStream in = resEntity.getContent();
            
            BufferedReader read = new BufferedReader(new InputStreamReader(in));
            
            String line = "";
            try {
            	 while((line = read.readLine())!=null ) {
                 	System.out.println(line);
                 }
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			in.close();
    		}
        } finally {
            response.close();
        }
		return null;
	}
	//上传文件
//	public static String upload(String url,File file){
//		String result = null;
//		try {
//			FileBody bin = null;
//			HttpClient httpclient = new DefaultHttpClient();
//			HttpPost httppost = new HttpPost(url);
//			bin = new FileBody(file);
// 
//			StringBody comment = new StringBody("A binary file of some kind");
//			MultipartEntity reqEntity = new MultipartEntity();
//			reqEntity.addPart("comment", comment);
//			reqEntity.addPart("data", bin);
//			 
//			httppost.setEntity(reqEntity);
//			 
//			HttpResponse response = httpclient.execute(httppost);
//			HttpEntity entity = response.getEntity(); 
//			result = null;
//			if (entity != null) {  
//				result = EntityUtils.toString(entity, "utf-8");
//				httppost.abort();    
//			}
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		} catch (ClientProtocolException e) {
//			e.printStackTrace();
//		} catch (ParseException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return result;
//	}
//	
	
	
	
	public static String getHttpPostJSONResponse(String url,Map<String,String> header,String json) {
		
		String APPLICATION_JSON = "application/json";
		String CONTENT_TYPE_TEXT_JSON = "text/json";
		
        HttpClient httpclient = new DefaultHttpClient();  
        HttpPost httppost = new HttpPost(url);
        
        if(header != null) {
        	Iterator<String> it = header.keySet().iterator();
        	while(it.hasNext()) {
        		String key = it.next();
        		String value = header.get(key);
        		httppost.addHeader(key, value);
        	}
        }
        
        
        if(json!= null && !"".equals(json)) {
        	String encoderJson = null;
//    		try {
//    			encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
//    		} catch (UnsupportedEncodingException e2) {
//    			e2.printStackTrace();
//    		}
        	
    		httppost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
            
            StringEntity se = null;
    		try {
    			se = new StringEntity(json,"utf-8");
    		} catch (Exception e1) {
    			e1.printStackTrace();
    		}
            se.setContentType(CONTENT_TYPE_TEXT_JSON);
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
            httppost.setEntity(se);
        }
        
        String result = null;
        
		try {
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity(); 
			if (entity != null) {  
				result = EntityUtils.toString(entity, "utf-8");
				httppost.abort();    
	        }  
		} catch (IOException e) {
			e.printStackTrace();
		}    
		return result;
        
	}
	
	/**
	 * 获取请求的IP地址
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static String getIpAddr(HttpServletRequest request) throws Exception { 
		
		String ip = request.getHeader("x-forwarded-for");    
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
		    ip = request.getHeader("Proxy-Client-IP");    
		}    
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
		    ip = request.getHeader("WL-Proxy-Client-IP");    
		}    
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
		    ip = request.getHeader("HTTP_CLIENT_IP");    
		}    
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
		    ip = request.getHeader("HTTP_X_FORWARDED_FOR");    
		}    
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
		        ip = request.getRemoteAddr();    
		}    
		return ip;  
		
	}
	
	public static void main(String[] args) {
		String url = "http://pinglun.yixun.com/json1.php?mod=reviews&act=getproperty&jsontype=str&pid=1948928&_ut=0&g_tk=5381&g_ty=jq&callback=jQuery151027612987083287976_1411456312615&_=1411456313505";
		Map<String,String> header = new HashMap<String,String>();
		header.put("Host", "pinglun.yixun.com");
		header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0");
		System.out.println(getHttpGetResponse(url,header));
	}
}
 